'''Copyright 2015 LinkedIn Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
 You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.'''

from modules.createExploit import *
from xml.dom import minidom
from xml.dom.minidom import Document
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement
from modules import common
from modules import filters

def write(obj):
    if not PackageNameInStrings():
        modifyStrings("packageName", filters.find_package())
    if hasattr(obj, "getType"):
        intentType = obj.getType()
        if intentType==exploitService.type:
            newId = modifyIntentID(exploitService.id)
            modifyStrings(newId, obj.getIntent())
            
        elif intentType in [exploitBroadcast.type]:
            newId = modifyIntentID(exploitBroadcast.id)
            keys = exploitBroadcast(obj).getExtra()
            for key in keys:
                modifyExtraKeys(newId, key)
            modifyStrings(newId, obj.getIntent())

        elif intentType in [exploitActivity.type]:
            newId = modifyIntentID(exploitActivity.id)
            keys = exploitActivity(obj).getExtra()
            for key in keys:
                modifyExtraKeys(newId, key)
            modifyStrings(newId, obj.getExportedActivity())

        elif intentType in [exploitContentProvider.type]:
            newId = modifyIntentID(exploitContentProvider.id)
            keys = exploitContentProvider(obj).getExtra()
            for key in keys:
                modifyExtraKeys(newId, key)
            modifyStrings(newId, obj.getIntent())

        elif intentType in [exploitReceiver.type]:
            newId = modifyIntentID(exploitReceiver.id)
            keys = exploitReceiver(obj).getExtra()
            for key in keys:
                modifyExtraKeys(newId, key)
            modifyStrings(newId, obj.getIntent())
            
def modifyIntentID(intentId):
    filename = common.exploitLocation + "/app/src/main/res/values/intentID.xml"
    insert_position = 0
    intentType = ""
    name = ""
    if intentId==exploitActivity.id:
        intentType = exploitActivity.type
        name = exploitActivity.parent
    elif intentId==exploitReceiver.id:
        intentType = exploitReceiver.type
        name = exploitReceiver.parent
    elif intentId==exploitContentProvider.id:
        intentType = exploitContentProvider.type
        name = exploitContentProvider.parent
    elif intentId==exploitBroadcast.id:
        intentType = exploitBroadcast.type
        name = exploitBroadcast.parent
    elif intentId==exploitService.id:
        intentType = exploitService.type
        name = exploitService.parent

    last_key = intentType + "0"
    document = ElementTree.parse(filename, None)
    for string_array in document.findall("string-array"):
        if string_array.attrib['name']==name:
            for item in string_array.getchildren():
                last_key = item.text
            break
        else:
            insert_position = insert_position + 1
    new_node = Element('item')
    new_node.text = intentType + str((int(last_key.split(intentType)[1])+1))
    document.iterfind("resources/string-array")
    root = document.getroot()
    root[insert_position].append(new_node)
    document.write(filename)
    return new_node.text

def modifyExtraKeys(intentName, key):
    filename = common.exploitLocation + "/app/src/main/res/values/extraKeys.xml"
    insert_position = 0
    flag = False
    document = ElementTree.parse(filename, None)
    root = document.getroot()
    for string_array in document.findall("string-array"):
        if string_array.attrib['name']==intentName:
            new_node = Element('item')
            new_node.text = key
            root[insert_position].append(new_node)
            flag = True
        else:
            insert_position = insert_position + 1
    if not flag:
        new_node = Element('string-array')
        new_node.attrib['name'] = intentName
        new_item_node = Element('item')
        new_item_node.text = key
        new_node.append(new_item_node)
        root.append(new_node)
    document.write(filename)

def modifyStrings(intentName, value):
    print "adding value to string: " + value
    filename = common.exploitLocation + "/app/src/main/res/values/strings.xml"
    document = ElementTree.parse(filename, None)
    root = document.getroot()
    if document.find(intentName) is None:
        new_node = Element('string')
        new_node.text = value
        new_node.attrib['name'] = intentName
        root.append(new_node)
    else:
        return
    document.write(filename)

def PackageNameInStrings():
    filename = common.exploitLocation + "/app/src/main/res/values/strings.xml"
    document = ElementTree.parse(filename, None)
    for string_array in document.findall("string"):
        if string_array.attrib['name']=="packageName":
            return True
    return False


